package com.jlcloud.core.secure.provider;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import com.jlcloud.core.tool.api.R;
import com.jlcloud.core.tool.api.ResultCode;
import com.jlcloud.core.tool.constant.JlCloudConstant;
import com.jlcloud.core.tool.jackson.JsonUtil;
import com.jlcloud.core.tool.utils.WebUtil;
import org.springframework.http.MediaType;

import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * ResponseProvider
 *
 * @author By: JlCloud <br>
 * @Package: com.jlcloud <br>
 * @CreateTime: 2024-12-03 21:45 <br>
 * @Copyright: 2021 www.jilianjituan.com Inc. All rights reserved. <br>
 * @Caution 注意：本内容仅限于冀联人力集团内部传阅，禁止外泄以及用于其他的商业目的 <br>
 */
@Slf4j
public class ResponseProvider {

	public static void logAuthFailure(HttpServletRequest request, HttpServletResponse response, String reason) {
		try {
			Map<String, String[]> parameterMap = request.getParameterMap();
			String paramsJson = JsonUtil.toJson(parameterMap);
			log.warn("{}，请求接口：{}，请求IP：{}，请求参数：{}", reason, request.getRequestURI(), WebUtil.getIP(request), paramsJson);
		} catch (Exception e) {
			log.error("日志记录失败", e);
		}
		ResponseProvider.write(response);
	}

	public static void write(HttpServletResponse response) {
		R result = R.fail(ResultCode.UN_AUTHORIZED);
		response.setCharacterEncoding(JlCloudConstant.UTF_8);
		response.addHeader(JlCloudConstant.CONTENT_TYPE_NAME, MediaType.APPLICATION_JSON_VALUE);
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		try {
			response.getWriter().write(Objects.requireNonNull(JsonUtil.toJson(result)));
		} catch (IOException ex) {
			log.error("ResponseProvider write IOException: ", ex);
		}
	}

}
